<template>
  <div class="permission-manage-container">
    <!-- 页面标题 + 操作栏 -->
    <div class="page-header">
      <h2 class="page-title">权限管理</h2>
      <div class="operation-bar">
        <el-input
            v-model="searchValue"
            placeholder="请输入权限名称或权限编码搜索"
            class="search-input"
            clearable
            @keyup.enter="handleSearch"
            style="width: 300px; height: 40px;"
        >
          <template #append>
            <el-button :icon="Search" @click="handleSearch" style="height: 100%; border-left: none;" />
          </template>
        </el-input>
        <el-button
            type="primary"
            @click="showAddDialog = true"
            icon="el-icon-plus"
            style="height: 40px; margin-left: 10px;"
        >
          添加权限
        </el-button>
        <el-button
            type="success"
            @click="showBatchAddDialog = true"
            icon="el-icon-copy-document"
            style="height: 40px; margin-left: 10px;"
        >
          批量添加
        </el-button>
      </div>
    </div>

    <!-- 权限表格 -->
    <el-card class="table-card">
      <el-skeleton v-if="loading" row-count="5" :columns="6" border></el-skeleton>

      <el-table
          v-else
          :data="filteredPermissionList"
          style="width: 100%"
          stripe
          border
          :header-cell-style="{ background: '#f5f7fa', color: '#333', fontWeight: 500 }"
          :cell-style="{ color: '#666' }"
          @row-click="handleRowClick"
      >
        <el-table-column prop="permissionId" label="权限 ID" width="100" align="center"></el-table-column>
        <el-table-column prop="permissionName" label="权限名称" width="200" align="center"></el-table-column>
        <el-table-column prop="permissionCode" label="权限编码" min-width="200" align="center"></el-table-column>
        <el-table-column min-width="180" label="操作" align="center">
          <template #default="{ row }">
            <el-button
                type="text"
                color="#409eff"
                size="small"
                @click.stop="editPermission(row)"
            >
              编辑
            </el-button>
            <el-button
                type="text"
                color="#f56c6c"
                size="small"
                @click.stop="handleDeleteConfirm(row.permissionId)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div v-if="!loading && filteredPermissionList.length === 0" class="empty-tip">
        <el-empty description="暂无权限数据"></el-empty>
      </div>
    </el-card>

    <!-- 编辑权限对话框 -->
    <el-dialog
        v-model="showEditDialog"
        title="编辑权限"
        width="500px"
        :close-on-click-modal="false"
        @open="handleEditDialogOpen"
    >
      <el-form
          :model="editPermissionInfo"
          label-width="100px"
          class="permission-form"
          :rules="permissionRules"
          ref="editPermissionFormRef"
          style="margin-top: 10px;"
      >
        <el-form-item label="权限 ID" disabled>
          <el-input v-model="editPermissionInfo.permissionId" style="width: 100%;"></el-input>
        </el-form-item>
        <el-form-item label="权限名称" prop="permissionName">
          <el-input
              v-model="editPermissionInfo.permissionName"
              placeholder="请输入权限名称（最多128字）"
              maxlength="128"
              style="width: 100%;"
          ></el-input>
        </el-form-item>
        <el-form-item label="权限编码" prop="permissionCode">
          <el-input
              v-model="editPermissionInfo.permissionCode"
              placeholder="请输入权限编码（如：sys:user:add）"
              maxlength="64"
              style="width: 100%;"
          ></el-input>
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showEditDialog = false">取消</el-button>
          <el-button type="primary" @click="updatePermission">确定保存</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 添加权限对话框 -->
    <el-dialog
        v-model="showAddDialog"
        title="添加权限"
        width="500px"
        :close-on-click-modal="false"
        @open="handleAddDialogOpen"
    >
      <el-form
          :model="addPermissionInfo"
          label-width="100px"
          class="permission-form"
          :rules="permissionRules"
          ref="addPermissionFormRef"
      >
        <el-form-item label="权限名称" prop="permissionName">
          <el-input
              v-model="addPermissionInfo.permissionName"
              placeholder="请输入权限名称"
              maxlength="128"
          ></el-input>
        </el-form-item>
        <el-form-item label="权限编码" prop="permissionCode">
          <el-input
              v-model="addPermissionInfo.permissionCode"
              placeholder="请输入权限编码（如：sys:user:add）"
              maxlength="64"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showAddDialog = false">取消</el-button>
        <el-button type="primary" @click="addPermission">确定添加</el-button>
      </template>
    </el-dialog>

    <!-- 批量添加权限对话框 -->
    <el-dialog
        v-model="showBatchAddDialog"
        title="批量添加权限"
        width="500px"
        :close-on-click-modal="false"
    >
      <el-form
          :model="batchAddInfo"
          label-width="100px"
          class="permission-form"
          :rules="batchAddRules"
          ref="batchAddFormRef"
      >
        <el-form-item label="权限标识" prop="mark">
          <el-input
              v-model="batchAddInfo.mark"
              placeholder="请输入权限标识（如：user）"
              maxlength="32"
          ></el-input>
          <div class="form-tip">标识将用于生成权限编码，如：sys:mark:add</div>
        </el-form-item>
        <el-form-item label="模块名称" prop="name">
          <el-input
              v-model="batchAddInfo.name"
              placeholder="请输入模块名称（如：用户）"
              maxlength="32"
          ></el-input>
          <div class="form-tip">名称将用于生成权限名称，如：新增用户</div>
        </el-form-item>
        <el-form-item>
          <div class="batch-preview">
            <div class="preview-title">将生成以下权限：</div>
            <div class="preview-list">
              <div v-if="batchAddInfo.mark && batchAddInfo.name">
                <div>1. 新增{{ batchAddInfo.name }} - sys:{{ batchAddInfo.mark }}:add</div>
                <div>2. 删除{{ batchAddInfo.name }} - sys:{{ batchAddInfo.mark }}:delete</div>
                <div>3. 更新{{ batchAddInfo.name }} - sys:{{ batchAddInfo.mark }}:update</div>
                <div>4. 查询{{ batchAddInfo.name }} - sys:{{ batchAddInfo.mark }}:list</div>
              </div>
              <div v-else class="preview-empty">请输入权限标识和模块名称预览</div>
            </div>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showBatchAddDialog = false">取消</el-button>
        <el-button type="primary" @click="batchAddPermissions">确定添加</el-button>
      </template>
    </el-dialog>

    <!-- 删除确认对话框 -->
    <el-dialog
        v-model="showDeleteDialog"
        title="删除确认"
        width="300px"
        :close-on-click-modal="false"
    >
      <p>确定要删除该权限吗？删除后不可恢复。</p>
      <template #footer>
        <el-button @click="showDeleteDialog = false">取消</el-button>
        <el-button type="danger" @click="deletePermission">确定删除</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive, watch } from 'vue';
import { ElMessage } from 'element-plus';
import httpRequest from "@/config/request";
import { Search } from "@element-plus/icons-vue";

// 权限列表相关状态
const permissionList = ref([]);
const filteredPermissionList = ref([]);
const loading = ref(false);
const searchValue = ref('');

// 对话框状态
const showAddDialog = ref(false);
const showEditDialog = ref(false);
const showDeleteDialog = ref(false);
const showBatchAddDialog = ref(false);
const deletePermissionId = ref('');

// 表单引用
const editPermissionFormRef = ref(null);
const addPermissionFormRef = ref(null);
const batchAddFormRef = ref(null);

// 编辑权限表单数据
const editPermissionInfo = reactive({
  permissionId: '',
  permissionName: '',
  permissionCode: ''
});

// 添加权限表单数据
const addPermissionInfo = reactive({
  permissionName: '',
  permissionCode: ''
});

// 批量添加权限表单数据
const batchAddInfo = reactive({
  mark: '',
  name: ''
});

// 表单验证规则
const permissionRules = reactive({
  permissionName: [
    { required: true, message: '请输入权限名称', trigger: 'blur' },
    { max: 128, message: '权限名称最多128个字符', trigger: 'blur' }
  ],
  permissionCode: [
    { required: true, message: '请输入权限编码', trigger: 'blur' },
    { max: 64, message: '权限编码最多64个字符', trigger: 'blur' },
    { pattern: /^[a-zA-Z0-9:_]+$/, message: '权限编码仅支持字母、数字、冒号和下划线', trigger: 'blur' }
  ]
});

// 批量添加验证规则
const batchAddRules = reactive({
  mark: [
    { required: true, message: '请输入权限标识', trigger: 'blur' },
    { max: 32, message: '权限标识最多32个字符', trigger: 'blur' },
    { pattern: /^[a-zA-Z0-9]+$/, message: '权限标识仅支持字母和数字', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '请输入模块名称', trigger: 'blur' },
    { max: 32, message: '模块名称最多32个字符', trigger: 'blur' }
  ]
});

// 获取所有权限
const getAllPermissions = async () => {
  try {
    loading.value = true;
    const res = await httpRequest.get('permission/list');
    if (res.data) {
      permissionList.value = res.data || [];
      filteredPermissionList.value = [...permissionList.value];
    } else {
      ElMessage.error(res.msg || '获取权限列表失败');
    }
  } catch (error) {
    console.error('获取权限列表失败', error);
    ElMessage.error('获取权限列表失败，请重试');
  } finally {
    loading.value = false;
  }
};

// 编辑对话框打开时加载数据
const handleEditDialogOpen = async () => {
  if (!editPermissionInfo.permissionId) return;

  try {
    const res = await httpRequest.get(`permission/detail?id=${editPermissionInfo.permissionId}`);
    if (res.data && res.data) {
      editPermissionInfo.permissionName = res.data.permissionName || '';
      editPermissionInfo.permissionCode = res.data.permissionCode || '';
    } else {
      ElMessage.error(res.msg || '获取权限详情失败');
      showEditDialog.value = false;
    }
  } catch (error) {
    console.error('获取权限详情失败', error);
    ElMessage.error('获取权限详情失败，请重试');
    showEditDialog.value = false;
  }
};

// 编辑权限
const editPermission = (row) => {
  if (!row?.permissionId) {
    ElMessage.warning('权限数据异常，请重试');
    return;
  }
  editPermissionInfo.permissionId = row.permissionId;
  editPermissionInfo.permissionName = row.permissionName || '';
  editPermissionInfo.permissionCode = row.permissionCode || '';
  showEditDialog.value = true;
};

// 更新权限
const updatePermission = async () => {
  try {
    const valid = await editPermissionFormRef.value.validate();
    if (!valid) return;

    const res = await httpRequest.post('permission/update', editPermissionInfo);
    if (res.data) {
      ElMessage.success('权限更新成功');
      showEditDialog.value = false;
      await getAllPermissions();
    } else {
      ElMessage.error(res.msg || '权限更新失败');
    }
  } catch (error) {
    console.error('更新权限失败', error);
    ElMessage.error('更新权限失败，请重试');
  }
};

// 搜索权限
const handleSearch = () => {
  const search = searchValue.value.trim().toLowerCase();
  filteredPermissionList.value = permissionList.value.filter(item =>
      (item.permissionName && item.permissionName.toLowerCase().includes(search)) ||
      (item.permissionCode && item.permissionCode.toLowerCase().includes(search))
  );
};

// 添加权限
const addPermission = async () => {
  try {
    const valid = await addPermissionFormRef.value.validate();
    if (!valid) return;

    const res = await httpRequest.post('permission/add', addPermissionInfo);
    if (res.data) {
      ElMessage.success('权限添加成功');
      showAddDialog.value = false;
      addPermissionInfo.permissionName = '';
      addPermissionInfo.permissionCode = '';
      await getAllPermissions();
    } else {
      ElMessage.error(res.msg || '权限添加失败');
    }
  } catch (error) {
    console.error('添加权限失败', error);
    ElMessage.error('添加权限失败，请重试');
  }
};

// 批量添加权限
const batchAddPermissions = async () => {
  try {
    const valid = await batchAddFormRef.value.validate();
    if (!valid) return;

    const res = await httpRequest.get(`permission/batch-add?mark=${batchAddInfo.mark}&name=${batchAddInfo.name}`);
    if (res.data) {
      ElMessage.success('批量添加权限成功');
      showBatchAddDialog.value = false;
      batchAddInfo.mark = '';
      batchAddInfo.name = '';
      await getAllPermissions();
    } else {
      ElMessage.error(res.msg || '批量添加权限失败');
    }
  } catch (error) {
    console.error('批量添加权限失败', error);
    ElMessage.error('批量添加权限失败，请重试');
  }
};

// 处理删除确认
const handleDeleteConfirm = (permissionId) => {
  deletePermissionId.value = permissionId;
  showDeleteDialog.value = true;
};

// 执行删除
const deletePermission = async () => {
  try {
    const res = await httpRequest.post('permission/delete', { id: deletePermissionId.value });
    if (res.data) {
      ElMessage.success('权限删除成功');
      showDeleteDialog.value = false;
      await getAllPermissions();
    } else {
      ElMessage.error(res.msg || '权限删除失败');
    }
  } catch (error) {
    console.error('删除权限失败', error);
    ElMessage.error('删除权限失败，请重试');
  }
};

// 打开添加对话框
const handleAddDialogOpen = () => {
  addPermissionInfo.permissionName = '';
  addPermissionInfo.permissionCode = '';
  if (addPermissionFormRef.value) {
    addPermissionFormRef.value.resetFields();
  }
};

// 表格行点击事件
const handleRowClick = (row) => {
  // 行点击事件，可根据需要添加选中效果
};

// 监听搜索值变化，实现实时搜索
watch(searchValue, (newVal) => {
  handleSearch();
});

// 页面初始化
onMounted(async () => {
  await getAllPermissions();
});
</script>

<style scoped>
.permission-manage-container {
  padding: 20px;
  background-color: #f5f6f8;
  min-height: calc(100vh - 110px);
  overflow: visible;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  flex-wrap: wrap;
  gap: 15px;
}

.table-card {
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
  border-radius: 4px;
  padding: 15px;
}

.empty-tip {
  padding: 50px 0;
  text-align: center;
}

.permission-form {
  margin-top: 20px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.batch-preview {
  margin-top: 10px;
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.preview-title {
  font-weight: 500;
  margin-bottom: 8px;
  color: #333;
}

.preview-list {
  font-size: 13px;
  color: #666;
  line-height: 1.8;
}

.preview-empty {
  color: #999;
  font-style: italic;
}

.form-tip {
  font-size: 12px;
  color: #999;
  margin-top: 5px;
}
</style>
